
import ssl
import requests
import json
import datetime
import glob

bdai_ak =  'ARAhQ54l9eTGmUhszx8iPZAF'         #在百度新建一个人脸识别项目就会给
bdai_sk = 'aG5urwxj3U1FWidG1BIFWp79oyNVEky7'  #在百度新建一个人脸识别项目就会给
header = {'Content-Type': 'application/json; charset=UTF-8'}  #要以此为请求头headers

class BdFaceDetectionGetAccessToken():
    '''\
    输入百度项目的ak值和sk值，返回各种接口
	
	实例化必传参数：
	bdai_ak:你的ak值
	bdai_sk:你的sk值
	header:请求头，一般不动默认值就好
	self.face_detection_url:人脸检测接口链接
	self.face_match_url:人脸对比接口链接

    
    '''

    header = {'Content-Type': 'application/json; charset=UTF-8'}  #要以此为请求头headers

    def __init__(self,
                 bdai_ak = 'ARAhQ54l9eTGmUhszx8iPZAF',
                 bdai_sk = 'aG5urwxj3U1FWidG1BIFWp79oyNVEky7',
                 header = {'Content-Type': 'application/json; charset=UTF-8'}
                 ):

        self.bdai_ak = bdai_ak
        self.bdai_sk = bdai_sk
        self.header = header
        self.access_token = self.test_now_access_token()
        

    def test(self):
        with open('access_token.json') as f:
                access_token_info = json.load(f)
        x = access_token_info['auto_now']
        y = datetime.datetime.now() - datetime.timedelta(days=30)
		
    def face_match_url(self):
        '''\
		return:人脸对比接口链接
		
        '''
        face_match_url = 'https://aip.baidubce.com/rest/2.0/face/v3/match?access_token={}'.format(self.access_token)
        return face_match_url
    def face_detection_url(self):
        '''\
        return:人脸检测接口链接
        
        '''
        face_detection_url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect\
?access_token={}'.format(self.access_token)
        return face_detection_url
    def test_now_access_token(self):
        '''\
        return:access_token值

        测试是否access_token值过期，如果过期则从新请求个新的access_token值
        
        '''
        if glob.glob('access_token.json'):
            with open('access_token.json') as f:
                access_token_info = json.load(f)
                if eval(access_token_info["auto_now"])>datetime.datetime.now() - datetime.timedelta(days=30):
                    
                    access_token = access_token_info["access_token"]
                                      
                else:
                    
                    access_token = self.get_access_token()

        else:

            access_token = self.get_access_token()

        return access_token            
                         

    def get_access_token(self):
        '''\
        return :最新token值
        '''
            
        host = 'https://aip.baidubce.com/oauth/2.0/token\
?grant_type=client_credentials&client_id={}\
&client_secret={}'.format(self.bdai_ak,self.bdai_sk)#拼接一个请求access_token值的连接
            
        response = requests.get(host,headers = self.header)
            
        content = response.json()
        access_token = content['access_token']#得出access_token值

        auto_now = repr(datetime.datetime.now())


        info = {"auto_now":auto_now,"access_token":access_token}

        with open('access_token.json','w') as f:

            json.dump(info,f)
            
        return access_token
            
def base64_image(img_path):
    '''\
    img_path :图片连接
    return :  返回图片的base64编译字符串
    '''
    import base64
    with open(img_path,'rb') as f:
        base64_data = base64.b64encode(f.read())

    return str(base64_data,'utf-8')

if __name__ == "__main__":

    #face_detection_url = face_detection_url(bdai_ak,bdai_sk,header)

    #face_detection_url ='https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=24.3c2a9906ad070c63a29809b16dc4c0d3.2592000.1534688195.282335-11564062'
    
    #img_path = 'C:/Users/Administrator/Desktop/bdaip_face_detection/微信图片_20180720211937.jpg'
    #img_path = 'C:/Users/Administrator/Desktop/bdaip_face_detection/微信图片_20180720211941.jpg'

    #now = result(face_detection_url,img_path,header)
    #print(now)
    x = BdFaceDetectionGetAccessToken().face_detection_url()
    print(x)








